package jehc.djshi.common.util.udp;

import jehc.djshi.common.base.BaseResult;
import jehc.djshi.common.constant.StatusConstant;
import jehc.djshi.common.constant.StatusConstant;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.*;
/**
 * @Desc UDP客户端工具类
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@Slf4j
public class UDPUtil {
    private static InetSocketAddress serverAddress = null;
    /**
     *
     * @param host
     * @param port
     * @return
     * @throws SocketException
     */
    public static InetSocketAddress getInetSocketAddress(String host, int port)throws SocketException {
        return (serverAddress == null)?new InetSocketAddress(host, port):serverAddress;
    }

    /**
     * 发送UDP消息并接收消息
     * @param udpParma
     * @return
     * @throws IOException
     */
    public static BaseResult send(UDPParma udpParma) throws IOException {
        BaseResult baseResult = new BaseResult();
        DatagramSocket socket = null;
        DatagramPacket response = null;
        try {
            if(udpParma.getUseLocalPort()){
                socket = new DatagramSocket();
            }else{
                socket = new DatagramSocket(null == udpParma.getLocalPort()?udpParma.getPort():udpParma.getLocalPort());//绑定本地接收端口（如果本地端口为空引用目标端口）
            }
            log.info("发送UDP数据:"+udpParma.message);
            byte[] data = udpParma.getMessage().getBytes(udpParma.getCharset());
            DatagramPacket request = new DatagramPacket(data, data.length, getInetSocketAddress(udpParma.getHost(),udpParma.getPort()));//发送指令代码
            if(udpParma.getReceive()){
                response = new DatagramPacket(new byte[1024], 1024);//创建接收数据包空间
            }
            socket.setSoTimeout(udpParma.soTimeout==null?10000:udpParma.soTimeout);//设置超时时间10秒
            socket.send(request);
            if(udpParma.getReceive()){
                socket.receive(response);
                String outRes = new String(response.getData(), 0, response.getLength(), udpParma.getCharset());
                log.info("发送UDP数据完毕{}",outRes);
                baseResult.setData(outRes);
            }
        } catch (UnsupportedEncodingException e) {
            log.error("UDP客户端发送失败{}",e);
            baseResult.setMessage("发送失败");
            baseResult.setStatus(StatusConstant.XT_PT_STATUS_VAL_500);
        }finally {
            if(null != socket){
                socket.close();
            }
        }
        return baseResult;
    }

//    /**
//     * 测试
//     * @param args
//     * @throws Exception
//     */
//    public static void main(String[] args) throws Exception {
//        for (int i = 0; i < 1 ; i++) {
//            log.info("----第 "+i+" 次发送UDP");
//            BaseResult baseResult = UDPUtil.sendReceive("192.168.4.200",11080,"{ \"MacID\": \"2020100001\",\"MsgID\": 1, \"Data\": [{\"Type\": 255}]}","ASCII");
//            log.info("baseResult:{}",baseResult);
//        }
//    }
}
